package xquery;

import java.util.ArrayList;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

import xquery.XPathData.Type;

public class XQueryTagExp extends XQuery {
	String tagName;
	XQExpression xquery;
	@Override
	public XPathData eval(XQContext context, ArrayList<Node> currentNodeList) {
		Document doc = context.getResultDoc();
		
		Node node = doc.createElement(tagName);
		
		XPathData result = xquery.eval(context, currentNodeList);
		if(result.type == Type.BOOL || result.type == Type.STRING)
			node.setTextContent(result.toString());
		else {
			for(Node n: result.getList()){
				Node newNode = null;
				if(n.getOwnerDocument() != doc)
				{
					newNode = doc.importNode(n, true);
				}
				else
				{
					newNode = n.cloneNode(true);
				}
				node.appendChild(newNode);
			}
		}
		
		ArrayList<Node> list = new ArrayList<Node>();
		list.add(node);
		return new XPathData(list);
	}
	public String toString()
	{
		StringBuffer sb = new StringBuffer("");
		sb.append("<"+ tagName + ">{ ");
		sb.append(xquery);
		sb.append(" }<\\" + tagName + ">\n");
		return sb.toString();
	}
}
